<template>
  <div class="card-box" :style="{'background-image': `url('${imgUrl}')`}">
    <div class="mengban">
      <div class="card-type">
        {{ getValue(card, 'hmember_type.name') }} 
        <tamplate v-if="showStatus">
          <van-tag v-if="card.status === 'Active'" type="success">{{ card.status_desc }}</van-tag>
          <van-tag v-else type="danger">{{ card.status_desc }}</van-tag>
        </tamplate>
      </div>
      <div v-if="card.status !== 'INITED' && showFaceValue" class="valid-date">
        有效期: {{ card.begin_date }} ~ {{ card.end_date }}, 面值: {{ getFaceValue(card) }}
      </div>
      <div v-if="card.status !== 'INITED' && showBalance" class="valid-date">
        有效期: {{ card.end_date }}, 剩余面值: {{ getBalance(card) }}
      </div>

      <div class="card-number">
        No. {{ card.member_number }}
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { type PropType, ref, onMounted } from 'vue'
import { get } from 'lodash-es'
import dayjs from 'dayjs';
import type { HMemberCard } from '@/api/wechat/types'

const getValue = get
const imgUrl = ref('')

const props = defineProps({
  card: {
    type: Object as PropType<HMemberCard>,
    required: true
  },
  showStatus: {
    type: Boolean,
    default: false
  },
  showBalance: {
    type: Boolean,
    default: false
  },
  showFaceValue: {
    type: Boolean,
    default: false
  }
})

onMounted(() => {
  imgUrl.value = props.card.hmember_type?.url!
})

defineOptions({
  name: 'HMemberCard'
})

const getBalance = (memberCard?: HMemberCard) => {
  if (memberCard) {
    if (get(memberCard, 'hmember_type.card_category') === 'counting') {
      return memberCard.limit! - memberCard.consumption_count! + '次'
    }

    if (memberCard.status === 'INITED') {
      return dayjs(memberCard.end_date).diff(memberCard.begin_date, 'days') + 1 + '天'
    }

    let day = dayjs(memberCard.end_date).diff(dayjs(), 'days') + 1
    if (day < 0) {
      day = 0
    }

    return day + '天'
  }

  return '-'
}

const getFaceValue = (card: HMemberCard) => {
  if (card.hmember_type?.card_category === 'counting') {
    return card.limit! + '次'
  }

  return dayjs(card.end_date).diff(dayjs(card.begin_date), 'days') + 1 + '天'
}

</script>

<style lang="scss">
.card-box {
  // background-image: url('https://img0.baidu.com/it/u=694576612,1773770605&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=319');
  background-repeat: no-repeat;
  background-size: cover;
  border-radius: 10px;
  width: 94%;
  margin: 0 auto;
  height: 180px;
  background-color: #eee;
  position: relative;

  .mengban {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-around;
  }
}

.card-type, .card-number, .valid-date {
  color: white;
  padding: 10px 20px;
  text-align: right;
}
</style>
